package com.robotserver.orders.jobs;

import com.robotserver.orders.service.PullTokensService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * 获取平台token
 * @author jianghan
 * @date 2019-11-08 10:06
 * @Description 更新平台所有的联盟token
 */
@Component
public class PullTokensJob {

    private static Logger logger = LoggerFactory.getLogger(PullTokensJob.class);

    @Autowired
    private PullTokensService pullTokensService;
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 每2分钟执行一次获取token
     */
//    @Scheduled(cron="0 0/2 * * * ?")
    public void execute(){
        logger.debug("PullTokensJob execute.");

        RLock lock = redissonClient.getLock("service_tokenall_sync_lock");
        boolean getlock = false;
        try {
            if (getlock=lock.tryLock(0,1, TimeUnit.MINUTES)) {
                logger.debug("execute right.");
                pullTokensService.pullTokens();
            }else {
                logger.debug("not execute right.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (getlock){
                lock.unlock();
                logger.debug("release lock.");
            }
        }
    }
}
